var io = require('socket.io').listen(8080);

io.set('log level', 2);

var sockets = [];

var waitingUsers = [];

function Client(socket, waiting) {
  this.socket = socket;
  this.waiting = !!waiting;
  this.partner = null;

  this.check = function() {
    var partner;

    if (waitingUsers.length === 0) {
      this.waiting = true;
      waitingUsers.push(this);
    } else {
      partner = waitingUsers.shift();
      partner.waiting = false;

      this.partner = partner;
      partner.partner = this;

      socket.emit('startCall');
    }
  };
  
  this.check();
};

io.sockets.on('connection', function(socket) {
  console.log('Client connected');

  var client = new Client(socket);

  ['addStream', 'remoteDescription', 'iceCandidate'].forEach(function(event) {
    socket.on(event, function(data) {
      if (client.partner) {
        client.partner.socket.emit(event, data);
      }
    });
  });

  socket.on('disconnect', function() {
    var index
      , partner;

    if (client.partner) {
      partner = client.partner;
      partner.partner = null;

      partner.socket.emit('endCall');

      partner.check();
    } else {
      index = waitingUsers.indexOf(client);

      if (index !== -1) {
        waitingUsers.splice(index, 1);
      }
    }
  });
});